<template>
    <view class="login">
        <!-- #ifdef H5 -->
        <view class="mpwx-login column-center">
            <image class="logo" style="margin-top: 10rpx" :src="appConfig.shop_login_logo"></image>

            <!-- <u-icon name="zhifubao-circle-fill" size="120" color="#1677ff" /> -->
            <!-- <view class="title xxl mt20 bold">支付宝授权登录</view> -->
            <view
                class="white br60 row-center btn alipay-button--login"
                v-if="isAlipayEnv()"
                @click="onAlipayLogin"
            >
                支付宝一键授权</view
            >
            <view class="code-login" @click="goCode"> 验证码登录 </view>
            <!-- <view class="muted mt20">支付宝授权登录后才可进行更多操作哦</view> -->
        </view>

        <!-- #endif -->

        <!-- #ifdef MP-ALIPAY -->
        <view class="mpwx-login column-center">
            <u-icon name="zhifubao-circle-fill" size="120" color="#1677ff" />
            <view class="title xxl mt20 bold">支付宝授权登录</view>
            <button
                size="lg"
                class="white br60 row-center btn"
                style="background-color: #1677ff"
                open-type="getAuthorize"
                @getAuthorize="onGetAuthorize"
                @error="onAuthError"
                scope="userInfo"
            >
                <text>支付宝一键授权</text>
            </button>
            <view class="code-login" @click="goCode"> 验证码登录 </view>
            <view class="muted mt20">支付宝授权登录后才可进行更多操作哦</view>
        </view>
        <!-- #endif -->

        <!-- #ifdef MP-WEIXIN -->
        <view class="mpwx-login">
            <image class="logo" :src="appConfig.shop_login_logo"></image>
            <button size="lg" class="white br5 row-center btn" @click="loginMP_WEIXIN">
                <!-- <image class="mr10 image" src="/static/images/icon_wechat.png"></image> -->
                <text>一键登录</text>
            </button>
            <view class="code-login" @click="goCode"> 验证码登录 </view>
            <view class="radio" @click="change">
                <radio class="select" :checked="agreement" color="#ff0000"></radio>
                <view class="labelText">
                    <text>我已阅读并同意</text>
                    <text @click.stop="goToExplain(0)">《服务协议》</text>
                    <text>和</text>
                    <text @click.stop="goToExplain(1)">《隐私协议》</text>
                </view>
            </view>
            <!-- <view class="avatar">
				<open-data type="userAvatarUrl"></open-data>
			</view>
			<view class="user-name mt20">
				<open-data type="userNickName"></open-data>
			</view>
			<view class="title xxl mt20 bold">微信授权登录</view>
			<button size="lg" class="white br60 row-center btn" @click="loginMP_WEIXIN">
				<image class="mr10 image" src="/static/images/icon_wechat.png"></image>
				<text>微信一键授权</text>
			</button>
			<view class="muted mt20">微信授权登录后才可进行更多操作哦</view> -->
        </view>
        <mplogin-popup
            v-model="showLoginPop"
            :logo="appConfig.shop_login_logo"
            :title="appConfig.name"
            @close="closePopup"
            @update="handleSubmitInfo"
        />
        <!--  #endif -->
    </view>
</template>

<script>
// #ifdef H5
import alipay from '../../utils/alipayjsapi.min.js'
// #endif

import { mapMutations, mapActions, mapGetters, mapState } from 'vuex'

import {
    accountLogin,
    codeLogin,
    sendSms,
    wxpLogin,
    smsCodeLogin,
    opLogin,
    authLogin,
    authAlipayLogin,
    alipayH5Login,
    getAlipayH5Config,
    updateUser
} from '@/api/app'

import { getUser, inputInviteCode } from '@/api/user'

import wechath5 from '@/utils/wechath5'

import { isWeixinClient, currentPage, client } from '@/utils/tools'

import { SMSType } from '@/utils/type'

import Cache from '@/utils/cache'

import { BACK_URL } from '@/config/cachekey'

import { getWxCode, getUserProfile } from '@/utils/login'
import { data } from '../../components/uview-ui/libs/mixin/mixin.js'

const loginType = {
    ACCOUNT_LOGIN: 0,
    SMS_CODE_LOGIN: 1
}

export default {
    data() {
        return {
            password: '',
            account: '',
            code: '',
            isWeixin: '',
            loginType: 0,
            smsCode: '',
            time: 59,
            canSendSms: true,
            telephone: '',
            showLoginPop: false,
            agreement: false
        }
    },

    computed: {
        ...mapGetters(['appConfig']),
        ...mapState(['token'])
    },

    methods: {
        ...mapMutations(['LOGIN']),
        ...mapActions(['getUser']),

        countDownFinish() {
            this.canSendSms = true
        },

        //判断是否是支付环境，这里主要是判断支付宝生活号
        isAlipayEnv() {
            const userAgent = navigator.userAgent.toLowerCase()
            return userAgent.indexOf('alipayclient') > -1
        },

        goCode() {
            // #ifdef MP-WEIXIN
            if (this.agreement == false) {
                this.$toast({
                    title: '请阅读并同意《服务协议》和《隐私协议》'
                })
                return
            }
            //#endif
            uni.navigateTo({
                url: '/pages/login/code'
            })
        },
        //同意/不同意政策
        async change() {
            this.agreement = !this.agreement
        },
        goToExplain(value) {
            uni.navigateTo({
                url: '/bundle/pages/server_explan/server_explan?type=' + value
            })
        },
        // H5 支付宝登录
        async onAlipayLogin() {
            await getAlipayH5Config().then((configs) => {
                if (configs.code == 1) {
                    const appid = configs.data.ali_app_id
                    // alert(JSON.stringify(appid))
                    // 获取AuthCode
                    alipay.getAuthCode(
                        {
                            appId: appid.toString(),
                            scopes: ['auth_user']
                        },
                        (res, err) => {
                            const authcode = res.authCode ?? res.authcode
                            // alert(JSON.stringify(res))
                            if ([2, 10, 11, 12, 15].includes(err)) {
                                return this.$toast({
                                    title: '授权失败，请重试'
                                })
                            }
                            uni.showLoading()
                            alipayH5Login({
                                code: authcode
                            })
                                .then((res) => {
                                    if (res.code == 1) {
                                        this.loginHandle(res.data)
                                    } else {
                                        this.$toast({
                                            title: res.msg
                                        })
                                    }
                                })
                                .finally(() => {
                                    this.$toast({
                                        title: res.msg
                                    })
                                    uni.hideLoading()
                                })
                        }
                    )
                }
            })
        },

        // 获取支付宝会员信息
        getAlipayUserInfo() {
            return new Promise((resolve, reject) => {
                my.getOpenUserInfo({
                    success: (res) => {
                        const userInfo = JSON.parse(res.response).response // 以下方的报文格式解析两层 response
                        resolve(userInfo)
                    },
                    fail: (res) => {
                        reject(res)
                    }
                })
            })
        },

        // 支付宝小程序登录
        async onGetAuthorize() {
            // 获取授权码
            const { authCode } = await my.getAuthCode({
                scopes: ['auth_base']
            })

            // 获取用户信息
            this.getAlipayUserInfo()
                .then((info) => {
                    uni.showLoading({
                        title: '登录中...',
                        mask: true
                    })

                    authAlipayLogin({
                        code: authCode,
                        avatar: info.avatar,
                        nickname: info.nickName ?? '用户'
                    })
                        .then((res) => {
                            uni.hideLoading()

                            if (res.code == 1) {
                                this.loginHandle(res.data)
                            } else {
                                this.$toast({
                                    title: res.msg
                                })
                            }
                        })
                        .catch((err) => {
                            uni.hideLoading()
                            this.$toast({
                                title: '登录失败'
                            })
                        })
                })
                .catch((err) => {
                    this.$toast({
                        title: '获取不到用户信息'
                    })
                    console.log(err)
                })
        },

        onAuthError() {
            console.log('Auth Error ....')
        },
        // 微信小程序登录
        async loginMP_WEIXIN() {
            if (this.agreement == false) {
                this.$toast({
                    title: '请阅读并同意《服务协议》和《隐私协议》'
                })
                return
            }
            // 获取用户信息
            const { userInfo } = await getUserProfile()
            // 获取用户授权码
            const wxCode = await getWxCode()

            uni.showLoading({
                title: '登录中...',
                mask: true
            })
            // 登录处理
            authLogin({
                code: wxCode,
                nickname: userInfo.nickName,
                headimgurl: userInfo.avatarUrl
            })
                .then(({ code, data, msg }) => {
                    if (code !== 1) throw msg
                    if (data.is_new_user) {
                        uni.hideLoading()
                        this.showLoginPop = true
                        this.loginData = data
                    } else {
                        this.loginHandle(data)
                    }
                })
                .catch((errMsg) => {
                    this.$toast({
                        title: errMsg
                    })
                })
        },

        // 账号登录
        async loginFun() {
            const { account, password, telephone, smsCode } = this
            if (this.loginType == 0) {
                const { code, data } = await accountLogin({
                    account,
                    password,
                    client: client
                })
                if (code == 1) {
                    this.loginHandle(data)
                }
            } else {
                if (!telephone) {
                    this.$toast({
                        title: '请填写手机号'
                    })
                    return
                }
                if (!smsCode) {
                    this.$toast({
                        title: '请填写手机验证码'
                    })
                    return
                }
                smsCodeLogin({
                    account: telephone,
                    code: smsCode
                }).then((res) => {
                    if (res.code == 1) {
                        this.loginHandle(res.data)
                    }
                })
            }
        },

        // 登录结果处理
        async loginHandle(data) {
            this.LOGIN(data)
            uni.hideLoading()
            const inviteCode = Cache.get('INVITE_CODE')
            console.log(inviteCode)
            if (inviteCode) {
                inputInviteCode({
                    code: inviteCode
                })
            }
            // #ifdef H5
            location.replace('/mobile' + (Cache.get(BACK_URL) || '/'))
            Cache.remove(BACK_URL)
            //#endif
            // #ifdef MP-WEIXIN  || APP-PLUS || MP-ALIPAY
            //判断是否开启强制绑定
            await getUser().then((res) => {
                if (res.code == 1) {
                    if (res.data.need_bind) {
                        //判断是否开启强制绑定手机号
                        uni.navigateTo({
                            url: '/pages/login/code?type=1'
                        })
                    } else {
                        console.log(1111)
                        uni.navigateBack({
                            success() {
                                // 刷新上一页
                                const { onLoad, options } = currentPage()
                                onLoad && onLoad(options)
                            }
                        })
                    }
                }
            })

            //#endif
        },

        changeLoginType() {
            if (this.loginType == loginType.ACCOUNT_LOGIN) {
                this.loginType = loginType.SMS_CODE_LOGIN
            } else if (this.loginType == loginType.SMS_CODE_LOGIN) {
                this.loginType = loginType.ACCOUNT_LOGIN
            }
        },

        // 发送验证码
        $sendSms() {
            if (this.canSendSms == false) {
                return
            }
            if (!this.telephone) {
                this.$toast({
                    title: '请填写手机号信息～'
                })
                return
            }

            sendSms({
                mobile: this.telephone,
                key: SMSType.LOGIN
            }).then((res) => {
                if (res.code == 1) {
                    this.canSendSms = false
                    this.$refs.countDown.start()
                    this.$toast({
                        title: res.msg
                    })
                }
            })
        },
        async handleSubmitInfo(e) {
            const loginData = this.loginData || {}
            const res = await updateUser(e, loginData.token)
            if (res.code == 1) {
                this.loginHandle(loginData)
            }
        },
        closePopup() {
            this.showLoginPop = false
        }
    },

    onShow() {
        try {
            const value = uni.getStorageSync('TOKEN')
            if (value) {
                console.log(value) // 输出的就是缓存中的数据
                uni.switchTab({
                    url: '/pages/index/index'
                })
            } else {
                console.log('没有找到缓存数据')
            }
        } catch (e) {
            // 处理异常情况，例如缓存被禁用等
            console.error('获取缓存失败', e)
        }
    },
    async onLoad(option) {
        // #ifdef H5
        // H5微信登录
        this.isWeixin = isWeixinClient()
        if (this.isLogin) {
            uni.switchTab({
                url: '/pages/index/index'
            })
            return
        }
        if (this.isWeixin) {
            const { code } = option
            if (code) {
                const data = await wechath5.authLogin(code)
                this.loginHandle(data)
            } else {
                wechath5.getWxUrl()
            }
        }
        // #endif
    }
}
</script>
<style lang="scss" scoped>
page {
    // background: url('/static/images/login_bg.png');
    text-align: center;

    .login {
        height: 100vh;

        .mpwx-login {
            height: 100%;
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;

            .logo {
                height: 92rpx;
                margin-top: 300rpx;
                width: 344rpx;
            }

            .radio {
                position: fixed;
                bottom: 150rpx;
                display: flex;
                justify-content: center;
                align-items: center;
                margin-top: 40rpx;

                .select {
                    color: #ff0000 !important;
                }

                .labelText {
                    text {
                        &:nth-of-type(2n) {
                            color: #2482ee;
                        }

                        &:nth-of-type(2n + 1) {
                            color: #666666;
                        }
                    }
                }
            }

            // .avatar {
            // 	display: inline-block;
            // 	width: 120rpx;
            // 	height: 120rpx;
            // 	border-radius: 50%;
            // 	border: 1px solid #eee;
            // 	overflow: hidden;
            // }

            // .user-name {
            // 	height: 40rpx;
            // }

            // .image {
            // 	width: 50rpx;
            // 	height: 50rpx;
            // }

            .btn {
                background-color: #2482ee;
                width: 580rpx;
                margin: 400rpx auto 0;
            }
        }

        .h5-login {
            padding-top: 100rpx;
            display: flex;
            flex-direction: column;
            align-items: center;
            height: 100%;
            box-sizing: border-box;

            .logo {
                width: 280rpx;
                height: 80rpx;
                margin-bottom: 50rpx;
            }

            .input {
                width: 670rpx;
                border-bottom: $-solid-border;
                margin-top: 30rpx;
            }

            .sms-btn {
                border: 1px solid $-color-primary;
                width: 176rpx;
                height: 60rpx;
                box-sizing: border-box;
            }

            .wx-login {
                margin-top: 60rpx;

                .image {
                    margin-top: 40rpx;
                    width: 80rpx;
                    height: 80rpx;
                }
            }
        }
    }

    .alipay-button--login {
        height: 80rpx;
        line-height: 80rpx;
        background-color: #1677ff !important;
    }
}

.uni-checkbox-input-checked,
.uni-radio-input-checked,
.uni-switch-input-checked {
    background-color: #5fb878 !important;
    border-color: #5fb878 !important;
    color: #fff !important;
}

.code-login {
    color: #2482ee;
    font-size: 32rpx;
    margin-top: 50rpx;
}
</style>
